/**
 * 
 */
package com.oron3.bouncer.genericgl;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLSurfaceView;
import android.opengl.GLU;

import com.oron3.bouncer.objects.shapes.Point;

/**
 * @author Ofek
 *
 */
public class GLWorldRenderer implements GLSurfaceView.Renderer {
	protected final Projector projector;
	protected int width;
	protected int height;
	protected final GLWorld world;

	/**
	 * 
	 */
	public GLWorldRenderer(final GLWorld glWorld) {
		projector = new Projector();
		world = glWorld;
		world.setProjector(projector);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.microedition.khronos.opengles.GL10, javax.microedition.khronos.egl.EGLConfig)
	 */
	@Override
	public void onSurfaceCreated(final GL10 gl, final EGLConfig config) {
		gl.glEnable(GL10.GL_DITHER);
		gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
		gl.glHint(GL10.GL_LINE_SMOOTH_HINT, GL10.GL_NICEST);
		gl.glHint(GL10.GL_POINT_SMOOTH_HINT, GL10.GL_NICEST);
		gl.glClearColor(1f, 1f, 1f, 1f);
		gl.glEnable(GL10.GL_CULL_FACE);
		gl.glCullFace(GL10.GL_FRONT);
		gl.glShadeModel(GL10.GL_SMOOTH);
		gl.glEnable(GL10.GL_DEPTH_TEST);
		gl.glDepthFunc( GL10.GL_ALWAYS );
		gl.glDepthMask( true );
		gl.glEnable(GL10.GL_TEXTURE_2D);

		gl.glEnable(GL10.GL_BLEND);
		gl.glBlendFunc(GL10.GL_SRC_ALPHA,GL10.GL_ONE_MINUS_SRC_ALPHA);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(javax.microedition.khronos.opengles.GL10, int, int)
	 */
	@Override
	public void onSurfaceChanged(final GL10 gl, final int width, final int height) {
		this.width = width;
		this.height = height;
		projector.setCurrentView(0, 0, width, height);
		final float ratio = (float) width / height;
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();
		//		GLU.gluPerspective(gl /* field of view in degree */, 90.0f,
		//				/* aspect ratio */ratio,
		//				/* Z near */0.001f, /* Z far */1000f);
		gl.glFrustumf(-ratio, ratio, -1, 1, 1, 1000);
		projector.initCurrentProjection(gl);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.opengl.GLSurfaceView.Renderer#onDrawFrame(javax.microedition.khronos.opengles.GL10)
	 */
	@Override
	public void onDrawFrame(final GL10 gl) {
		final Point eye = world.getEye();
		final Point center = world.getCenter();
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glLoadIdentity();
		GLU.gluLookAt(gl, eye.x, eye.y, eye.z, /* eye */
				center.x, center.y, center.z, /* center */
				0f, 0f, 1f); /* up is Z */
		projector.initCurrentModelView(gl);
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

		world.draw((MatrixTrackingGL) gl);
	}

}
